﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .text-input {
        margin-bottom: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }

    .texts-input {
        margin-top: 20px; /* 每个文本框下方留出20px的间距 */
        width: 100%;
    }

    /* 表格样式优化 */
    .layui-table {
        border-collapse: collapse;
        width: 1200px;
    }

    .layui-table th,
    .layui-table td {
        text-align: center;
        vertical-align: middle;
        padding: 8px 12px;
        border: 1px solid #e6e6e6;
        word-wrap: break-word;
        word-break: break-all;
        height: 40px;
        line-height: 24px;
    }

    .layui-table th {
        background-color: #f2f2f2;
        font-weight: bold;
        height: 42px;
    }

    .layui-table tbody tr {
        height: 40px;
    }

    .layui-table tbody tr:hover {
        background-color: #f8f8f8;
    }

    /* 操作按钮样式 */
    .layui-table .layui-btn {
        margin: 2px;
        padding: 4px 8px;
        font-size: 12px;
        height: 26px;
        line-height: 18px;
    }

    /* 确保复选框垂直居中 */
    .layui-table input[type="checkbox"] {
        vertical-align: middle;
    }

    /* 空数据行样式 */
    .empty-row {
        height: 60px;
        line-height: 60px;
        color: #999;
        font-style: italic;
    }

    /* 状态标签样式 */
    .status-badge {
        padding: 2px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: normal;
        display: inline-block;
        min-width: 50px;
    }

    .status-1 { background-color: #f0f0f0; color: #666; } /* 草稿 */
    .status-2 { background-color: #e1f5fe; color: #0277bd; } /* 已确认 */
    .status-3 { background-color: #fff3e0; color: #f57c00; } /* 审核中 */
    .status-4 { background-color: #e8f5e8; color: #2e7d32; } /* 已审批 */
    .status-5 { background-color: #e3f2fd; color: #1976d2; } /* 已完成 */
    .status-6 { background-color: #ffebee; color: #d32f2f; } /* 已拒绝 */
    .status-0 { background-color: #f5f5f5; color: #999; } /* 未知 */
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="search-box">
        <div class="layui-form" lay-filter="searchForm">
            <div class="layui-form-item texts-input" style="margin-bottom: 0;">
                <label class="layui-form-label text-input">维修单编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="repairCode" name="repairCode" placeholder="请输入维修单编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">维修单名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="repairName" name="repairName" placeholder="请输入维修单名称" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">设备编号:</label>
                <div class="layui-input-inline">
                    <input type="text" id="deviceCode" name="deviceCode" placeholder="请输入设备编号" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">设备名称:</label>
                <div class="layui-input-inline">
                    <input type="text" id="deviceName" name="deviceName" placeholder="请输入设备名称" autocomplete="off" class="layui-input">
                </div>
                <label class="layui-form-label">维修结果:</label>
                <div class="layui-input-inline">
                    <input type="text" id="repairResults" name="repairResults" placeholder="请输入维修结果" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">单据状态:</label>
                    <div class="layui-input-inline">
                        <select name="documentStatus" id="documentStatus">
                            <option value="">请选择单据状态</option>
                            <option value="1">草稿</option>
                            <option value="2">已确认</option>
                            <option value="3">审核中</option>
                            <option value="4">已审批</option>
                            <option value="5">已完成</option>
                            <option value="6">已拒绝</option>
                        </select>
                    </div>
                    <button type="button" class="layui-btn layui-bg-blue" lay-submit lay-filter="searchBtn"><i class="layui-icon layui-icon-search"></i>搜索</button>
                    <button type="reset" class="layui-btn layui-btn-primary" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button type="button" class="layui-btn layui-bg-blue" onclick="addRepair()"><i class="layui-icon layui-icon-addition"></i>新增</button>
                    <button class="layui-btn layui-bg-red" onclick="deleteRepair()"><i class="layui-icon &#xe640; layui-icon-delete"></i>批量删除</button>
                </div>
            </div>
        </div>
    </div>
    <div class="page-container">
        @Html.AntiForgeryToken()
        <table class="layui-table" lay-size="lg">
            <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="selectAll" lay-skin="primary">
                    </th>
                    <th>维修单编号</th>
                    <th>维修单名称</th>
                    <th>设备编号</th>
                    <th>设备名称</th>
                    <th>保修日期</th>
                    <th>维修完成日期</th>
                    <th>验收日期</th>
                    <th>维修结果</th>
                    <th>维修人员</th>
                    <th>验收人员</th>
                    <th>单据状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody id="tb">
            </tbody>
        </table>
        <div id="pagination"></div>
    </div>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    layui.use(['form', 'laypage', 'table'], function () {
        var form = layui.form;
        var laypage = layui.laypage;
        var table = layui.table;

        var selectedIds = []; // 存储选中的ID

        // 页面加载时获取数据
        loadRepairData();

        // 搜索按钮事件
        form.on('submit(searchBtn)', function (data) {
            loadRepairData();
            return false;
        });

        // 重置按钮事件
        $('#resetBtn').click(function () {
            $('#repairCode').val('');
            $('#repairName').val('');
            $('#deviceCode').val('');
            $('#deviceName').val('');
            $('#repairResults').val('');
            $('#documentStatus').val('');
            form.render('select');
            loadRepairData();
        });

        // 全选功能
        $('#selectAll').change(function () {
            var isChecked = $(this).is(':checked');
            $('input[name="itemCheckbox"]').prop('checked', isChecked);
            
            if (isChecked) {
                selectedIds = [];
                $('input[name="itemCheckbox"]').each(function () {
                    selectedIds.push($(this).val());
                });
            } else {
                selectedIds = [];
            }
        });

        // 单项选择
        $(document).on('change', 'input[name="itemCheckbox"]', function () {
            var id = $(this).val();
            if ($(this).is(':checked')) {
                if (selectedIds.indexOf(id) === -1) {
                    selectedIds.push(id);
                }
            } else {
                selectedIds = selectedIds.filter(function (item) {
                    return item !== id;
                });
            }

            // 更新全选状态
            var totalCheckboxes = $('input[name="itemCheckbox"]').length;
            var checkedCheckboxes = $('input[name="itemCheckbox"]:checked').length;
            $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
        });
    });

    // 加载维修单数据
    function loadRepairData() {
        var searchData = {
            RepairCode: $('#repairCode').val() || null,
            RepairName: $('#repairName').val() || null,
            DeviceCode: $('#deviceCode').val() || null,
            DeviceName: $('#deviceName').val() || null,
            RepairResults: $('#repairResults').val() || null,
            DocumentStatus: $('#documentStatus').val() ? parseInt($('#documentStatus').val()) : null
        };

        $.ajax({
            url: '/RepairOrders/GetRepair',
            type: 'GET',
            data: searchData,
            success: function (data) {
                renderTable(data);
            },
            error: function (xhr, status, error) {
                layer.msg('加载数据失败: ' + error, { icon: 2 });
                console.log('Error details:', xhr.responseText);
            }
        });
    }

    // 渲染表格
    function renderTable(data) {
        var tbody = $('#tb');
        tbody.empty();

        if (data.length === 0) {
            tbody.append('<tr><td colspan="13" class="empty-row">暂无数据</td></tr>');
            return;
        }

        // 前端排序：按ID升序排列，确保数据顺序固定，修改后位置不变
        data.sort(function(a, b) {
            return (a.id || 0) - (b.id || 0);
        });

        data.forEach(function (item) {
            var statusText = getStatusText(item.documentStatus);
            // 格式化日期显示
            var warrantyDate = formatDate(item.warrantyDate);
            var repairDate = formatDate(item.repairDate);
            var acceptanceDate = formatDate(item.acceptanceDate);
            
            var row = `
                <tr>
                    <td>
                        <input type="checkbox" name="itemCheckbox" value="${item.id || ''}" lay-skin="primary">
                    </td>
                    <td>${item.repairCode || '-'}</td>
                    <td>${item.repairName || '-'}</td>
                    <td>${item.deviceCode || '-'}</td>
                    <td>${item.deviceName || '-'}</td>
                    <td>${warrantyDate}</td>
                    <td>${repairDate}</td>
                    <td>${acceptanceDate}</td>
                    <td>${item.repairResults || '-'}</td>
                    <td>${item.repairPersonnel || '-'}</td>
                    <td>${item.acceptancePersonnel || '-'}</td>
                    <td><span class="status-badge status-${item.documentStatus || 0}">${statusText}</span></td>
                    <td>
                        <button class="layui-btn layui-btn-xs" onclick="editSingleRepair(${item.id || 0})">
                            <i class="layui-icon layui-icon-edit"></i> 编辑
                        </button>
                        <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteSingleRepair(${item.id || 0})">
                            <i class="layui-icon layui-icon-delete"></i> 删除
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });

        // 重新渲染表单元素
        layui.form.render();
    }

    // 获取状态文本
    function getStatusText(status) {
        switch (status) {
            case 1: return '草稿';
            case 2: return '已确认';
            case 3: return '审核中';
            case 4: return '已审批';
            case 5: return '已完成';
            case 6: return '已拒绝';
            default: return '未知';
        }
    }

    // 格式化日期显示
    function formatDate(dateString) {
        if (!dateString) return '-';
        
        var date = new Date(dateString);
        if (isNaN(date.getTime())) return '-';
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        
        return `${year}-${month}-${day}`;
    }

    // 新增维修单
    function addRepair() {
        location.href = "/RepairOrders/AddShowRepairView";
    }

    // 编辑选中的维修单
    function editRepair() {
        var selectedIds = [];
        $('input[name="itemCheckbox"]:checked').each(function () {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            layer.msg('请选择要编辑的维修单', { icon: 0 });
            return;
        }

        if (selectedIds.length > 1) {
            layer.msg('只能选择一条记录进行编辑', { icon: 0 });
            return;
        }

        // 跳转到编辑页面，传递ID参数
        location.href = "/RepairOrders/UpdateShowRepairView?id=" + selectedIds[0];
    }

    // 编辑单个维修单
    function editSingleRepair(id) {
        location.href = "/RepairOrders/UpdateShowRepairView?id=" + id;
    }

    // 批量删除选中的维修单
    function deleteRepair() {
        var selectedIds = [];
        $('input[name="itemCheckbox"]:checked').each(function () {
            var id = $(this).val();
            if (id && id > 0) {
                selectedIds.push(parseInt(id));
            }
        });

        if (selectedIds.length === 0) {
            layer.msg('请选择要删除的维修单', { icon: 0 });
            return;
        }

        var confirmText = selectedIds.length === 1 
            ? '确定要删除这条维修单吗？' 
            : `确定要删除选中的 ${selectedIds.length} 条维修单吗？`;

        layer.confirm(confirmText, { 
            icon: 3, 
            title: '批量删除确认',
            btn: ['确定删除', '取消']
        }, function (index) {
            // 显示加载提示
            var loadIndex = layer.load(1, { shade: [0.1, '#fff'] });
            
            // 调用批量删除接口
            $.ajax({
                url: '/RepairOrders/BatchDeleteRepair',
                type: 'POST',
                data: { 
                    ids: selectedIds,
                    '__RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                traditional: true, // 重要: 让jQuery正确序列化数组参数
                success: function (result) {
                    layer.close(loadIndex); // 关闭加载提示
                    
                    if (result > 0) {
                        var successMsg = selectedIds.length === 1 
                            ? '删除成功' 
                            : `成功删除 ${result} 条维修单`;
                            
                        if (result < selectedIds.length) {
                            successMsg += `，${selectedIds.length - result} 条删除失败`;
                        }
                        
                        layer.msg(successMsg, { 
                            icon: 1,
                            time: 1500,
                            end: function() {
                                // 重新加载数据
                                loadRepairData();
                                // 清空选择
                                $('#selectAll').prop('checked', false);
                            }
                        });
                    } else {
                        layer.msg('删除失败，请重试', { 
                            icon: 2,
                            time: 3000
                        });
                    }
                    layer.close(index); // 关闭确认对话框
                },
                error: function (xhr, status, error) {
                    layer.close(loadIndex); // 关闭加载提示
                    
                    var errorMsg = '批量删除失败';
                    if (xhr && xhr.status) {
                        if (xhr.status === 404) {
                            errorMsg = '部分维修单不存在或已被删除';
                        } else if (xhr.status === 500) {
                            errorMsg = '服务器内部错误，请稍后重试';
                        } else if (xhr.status === 403) {
                            errorMsg = '没有权限执行此操作';
                        }
                    }
                    
                    layer.msg(errorMsg, { 
                        icon: 2,
                        time: 3000,
                        end: function() {
                            // 即使失败也刷新数据，因为可能部分删除成功
                            loadRepairData();
                            $('#selectAll').prop('checked', false);
                        }
                    });
                    console.log('批量删除失败详情:', xhr);
                }
            });
        }, function (index) {
            // 取消按钮回调
            layer.close(index);
        });
    }

    // 删除单个维修单
    function deleteSingleRepair(id) {
        // 验证ID是否有效
        if (!id || id <= 0) {
            layer.msg('无效的维修单ID', { icon: 0 });
            return;
        }

        layer.confirm('确定要删除这条维修单吗？', { 
            icon: 3, 
            title: '删除确认',
            btn: ['确定删除', '取消']
        }, function (index) {
            // 显示加载提示
            var loadIndex = layer.load(1, { shade: [0.1, '#fff'] });
            
            $.ajax({
                url: '/RepairOrders/DeleteRepair',
                type: 'POST',
                data: { id: id },
                headers: {
                    'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                },
                success: function (result) {
                    layer.close(loadIndex); // 关闭加载提示
                    layer.msg('删除成功', { 
                        icon: 1,
                        time: 1500,
                        end: function() {
                            // 重新加载数据
                            loadRepairData();
                        }
                    });
                    layer.close(index); // 关闭确认对话框
                },
                error: function (xhr, status, error) {
                    layer.close(loadIndex); // 关闭加载提示
                    
                    var errorMsg = '删除失败';
                    if (xhr.status === 404) {
                        errorMsg = '维修单不存在或已被删除';
                    } else if (xhr.status === 500) {
                        errorMsg = '服务器内部错误，请稍后重试';
                    } else if (xhr.status === 403) {
                        errorMsg = '没有权限执行此操作';
                    } else if (error) {
                        errorMsg = '删除失败: ' + error;
                    }
                    
                    layer.msg(errorMsg, { 
                        icon: 2,
                        time: 3000
                    });
                    console.log('删除失败详情:', {
                        status: xhr.status,
                        statusText: xhr.statusText,
                        error: error,
                        response: xhr.responseText
                    });
                }
            });
        }, function (index) {
            // 取消按钮回调
            layer.close(index);
        });
    }
</script>